import time
from server.utils.handleFile import readJSFile, getDirCount, writeToJSFile

table_name = 'graph_describe'


# 获取描述信息
def get_describe(gid):
    data = readJSFile("server/database/resource/data/" + str(gid) + "/graph_describe.json")
    return data


# 获取图数量信息
def get_count(uid):
    return getDirCount("server/database/resource/data")


# 更新描述信息
def update_describe(gid, name='', note='', uid='', img=[], ctime='', utime='', etime='', otype=''):
    # 仅更新值不为-1的内容
    graph_describe_data = get_describe(gid)

    if name is not None and len(name) > 0:
        graph_describe_data['name'] = name

    if note is not None:
        graph_describe_data['note'] = note

    if uid is not None and len(uid) > 0:
        graph_describe_data['uid'] = uid

    if img is not None:
        graph_describe_data['img'] = img

    if otype is not None and len(otype) > 0:
        if otype == '1':
            if utime is None or len(utime) == 0:
                utime = int(time.time())
            graph_describe_data['utime'] = utime

        elif otype == '2':
            if etime is None or len(etime) == 0:
                etime = int(time.time())
            graph_describe_data['etime'] = etime

        graph_describe_data['otype'] = otype

    else:
        if ctime is not None and len(ctime) > 0:
            if ctime is None or len(ctime) == 0:
                ctime = int(time.time())
            graph_describe_data['ctime'] = ctime

            graph_describe_data['otype'] = otype

    # 更新
    try:
        writeToJSFile(graph_describe_data, "server/database/resource/data/" + str(gid) + "/graph_describe.json")
        print(f'更新{table_name}信息成功，更新gid：{gid}')
        return 1
    except Exception as e:
        print(f'更新{table_name}信息失败：{e}')
        return e
